<template>
  <a-card>
    <template #title>
      <a-form>
        <a-row :gutter="16">

          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('注册渠道')">
              <a-select v-model:value="page.channel" allowClear>
                <a-select-option v-for="item in channelList" :key="item" :value="item">{{ item }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :xs="24">
            <a-form-item :label="$t('日期')">
              <a-range-picker v-model:value="page.timeValue" format="YYYY-MM-DD"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col style="text-align: right" :span="24">
            <a-button type="primary" @click="getTableData">{{ $t('查询') }}</a-button>
          </a-col>
        </a-row>
      </a-form>
      <a-table style="margin-top: 15px" :pagination="false" :columns="totalTableColumn"  :data-source="totalTableData" :scroll="{x:1000}"
               bordered>
      </a-table>

    </template>
    <a-table  :columns="tableColumn" :pagination="pagination" :loading="loading" :data-source="tableData" :scroll="{x:1000}"
              bordered>
      <template #seven="{record}">
        <span v-html="reduceRate(record.seven,record.six,record)"></span>
      </template>
      <template #eight="{record}">
        <span v-html="reduceRate(record.eight,record.seven,record)"></span>
      </template>
      <template #nine="{record}">
        <span v-html="reduceRate(record.nine,record.eight,record)"></span>
      </template>
      <template #ten="{record}">
        <span v-html="reduceRate(record.ten,record.nine,record)"></span>
      </template>
      <template #eleven="{record}">
        <span v-html="reduceRate(record.eleven,record.ten,record)"></span>
      </template>
      <template #twelve="{record}">
        <span v-html="reduceRate(record.twelve,record.eleven,record)"></span>
      </template>
      <template #thirteen="{record}">
        <span v-html="reduceRate(record.thirteen,record.twelve,record)"></span>
      </template>
      <template #fourteen="{record}">
        <span v-html="reduceRate(record.fourteen,record.thirteen,record)"></span>
      </template>
      <template #fifteen="{record}">
        <span v-html="reduceRate(record.fifteen,record.fourteen,record)"></span>
      </template>
      <template slot="sixteen" #sixteen="{record}">
        <span v-html="reduceRate(record.sixteen,record.fifteen,record)"></span>
      </template>
      <template #seventeen="{record}">
        <span v-html="reduceRate(record.seventeen,record.sixteen,record)"></span>
      </template>
      <template #eighteen="{record}">
        <span v-html="reduceRate(record.eighteen,record.seventeen,record)"></span>
      </template>
      <template #nineteen="{record}">
        <span v-html="reduceRate(record.nineteen,record.eighteen,record)"></span>
      </template>
      <template #twenty="{record}">
        <span v-html="reduceRate(record.twenty,record.nineteen,record)"></span>
      </template>
    </a-table>
  </a-card>
</template>

<script>
import {reactive, ref, toRefs, onMounted, computed, createVNode} from 'vue'
import {fetchTimeShareRegisterReport, fetchTimeShareRegisterTotal} from "@/api/report"
import locale from '@/locale'
import {selectChannelList} from "../../../api";
const {t} = locale.global;
import {dateFormatTimeStamp, defaultTimeDate} from '@/utils'
import deepcopy from "deepcopy";

const tableColumn = [
  {title: t('时间'), dataIndex: 'time', width: 150, align: 'center', fixed: 'left',},
  {
    title: '0-6', dataIndex: 'six', width: 100, align: 'center',
  },
  {title: '7', dataIndex: 'seven', width: 100, align: 'center', slots: {customRender: 'seven',}},
  {title: '8', dataIndex: 'eight', width: 100, align: 'center', slots: {customRender: 'eight',}},
  {title: '9', dataIndex: 'nine', width: 100, align: 'center', slots: {customRender: 'nine',}},
  {title: '10', dataIndex: 'ten', width: 100, align: 'center', slots: {customRender: 'ten',}},
  {title: '11', dataIndex: 'eleven', width: 100, align: 'center', slots: {customRender: 'eleven',}},
  {title: '12', dataIndex: 'twelve', width: 100, align: 'center', slots: {customRender: 'twelve',}},
  {title: '13', dataIndex: 'thirteen', width: 100, align: 'center', slots: {customRender: 'thirteen',}},
  {title: '14', dataIndex: 'fourteen', width: 100, align: 'center', slots: {customRender: 'fourteen',}},
  {title: '15', dataIndex: 'fifteen', width: 100, align: 'center', slots: {customRender: 'fifteen',}},
  {title: '16', dataIndex: 'sixteen', width: 100, align: 'center', slots: {customRender: 'sixteen',}},
  {title: '17', dataIndex: 'seventeen', width: 100, align: 'center', slots: {customRender: 'seventeen',}},
  {title: '18', dataIndex: 'eighteen', width: 100, align: 'center', slots: {customRender: 'eighteen',}},
  {title: '19', dataIndex: 'nineteen', width: 100, align: 'center', slots: {customRender: 'nineteen',}},
  {title: '20-23', dataIndex: 'twenty', width: 100, align: 'center', slots: {customRender: 'twenty',}},
]
const totalTableColumn = [
  {title: t('时间'), dataIndex: 'time', width: 150, align: 'center', fixed: 'left',},
  { title: '0-6', dataIndex: 'six', width: 100, align: 'center', },
  {title: '7', dataIndex: 'seven', width: 100, align: 'center', slots: {customRender: 'seven',}},
  {title: '8', dataIndex: 'eight', width: 100, align: 'center', slots: {customRender: 'eight',}},
  {title: '9', dataIndex: 'nine', width: 100, align: 'center', slots: {customRender: 'nine',}},
  {title: '10', dataIndex: 'ten', width: 100, align: 'center', slots: {customRender: 'ten',}},
  {title: '11', dataIndex: 'eleven', width: 100, align: 'center', slots: {customRender: 'eleven',}},
  {title: '12', dataIndex: 'twelve', width: 100, align: 'center', slots: {customRender: 'twelve',}},
  {title: '13', dataIndex: 'thirteen', width: 100, align: 'center', slots: {customRender: 'thirteen',}},
  {title: '14', dataIndex: 'fourteen', width: 100, align: 'center', slots: {customRender: 'fourteen',}},
  {title: '15', dataIndex: 'fifteen', width: 100, align: 'center', slots: {customRender: 'fifteen',}},
  {title: '16', dataIndex: 'sixteen', width: 100, align: 'center', slots: {customRender: 'sixteen',}},
  {title: '17', dataIndex: 'seventeen', width: 100, align: 'center', slots: {customRender: 'seventeen',}},
  {title: '18', dataIndex: 'eighteen', width: 100, align: 'center', slots: {customRender: 'eighteen',}},
  {title: '19', dataIndex: 'nineteen', width: 100, align: 'center', slots: {customRender: 'nineteen',}},
  {title: '20-23', dataIndex: 'twenty', width: 100, align: 'center', slots: {customRender: 'twenty',}},
]
export default {
  name: "TimeShareRegister",
  setup() {
    const formRef = ref(null)
    const state = reactive({
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        timeValue: defaultTimeDate(30)
      },
      tableRows: {},
      incomeDetailsVisible: false,
      tableData: [],
      totalTableData: [],
      systemUserList: [],
      channelList: [],
      loading:false
    })
    const pagination = computed(() => ({
      current: state.page.pageNum,
      total: state.page.total,
      pageSize: state.page.pageSize,
      showSizeChanger: true,
      showQuickJumper: true,
      pageSizeOptions: ['10', '50', '100', '200'],
      showTotal: total => total ,
      onChange: (page) => {
        state.page.pageNum = page
        method.getTableData()
      },
      onShowSizeChange: (page, size) => {
        state.page.pageNum = page
        state.page.pageSize = size
        method.getTableData()
      }
    }))
    const method = {
      async getTableData() {
        const [dateTimeStart, dateTimeEnd] = dateFormatTimeStamp(state.page.timeValue || [])
        const params = {
          dateTimeStart, dateTimeEnd,
          ...state.page,
        }
        delete params.timeValue
        state.loading = true
        const res = await fetchTimeShareRegisterReport(params)
        if (res.code === 1) {
          const {list, total} = res.data
          state.tableData = list
          state.page.total = total
          await  method.getTotal(params)
        }
        state.loading = false
      },
      async getTotal(params) {
        const res = await fetchTimeShareRegisterTotal(params)
        if (res.code === 1) {
          if (state.tableData.length > 0) {
            const average = res.data.find(item => item.type === 2)
            const totalData = res.data.find(item => item.type === 1)
            const averageData =  method.countAverageNum(average)
            state.totalTableData = [
              {...totalData, time: t('合计')},
              {...averageData, time: t('平均数')},
            ]
          } else {
            state.totalTableData = []
          }
        }
      },
      countAverageNum(data) {
        const averageObj = {}
        for (const key in data) {
          if (data[key]) {
            averageObj[key] = (data[key] / data['num']).toFixed(2)
          } else {
            averageObj[key] = 0
          }
        }
        return averageObj
      },
      // 计算增长率
      reduceRate(currentValue, previousValue, rows) {
        if (rows.time === t('合计') || rows.time === t('平均数')) {
          return `
        <div style="font-size: 16px;text-align: center;">${currentValue}</div>
        `
        }
        // 当前值
        const cur = currentValue || 0
        // 前一个值
        const pre = previousValue || 0
        const upValue = (cur - pre).toFixed(0)
        /**
         * @param curValue 当前值
         * @param upValue 增长值
         * @param trend up: 涨   flat:平
         * @return {string}
         */
        const formatText = (curValue, upValue, trend) => {
          const up = trend === 'up'
          return `
        <div style="font-size:16px;position:relative;">${curValue}
               <div style="color:${up ? 'red' : 'gray'};font-size:8px;position:absolute;top: -6px;right: 0px" >+${upValue <= 0 ? '0' : upValue}</div>
        </div>
        </div>
      `
        }
        if (upValue > 0) {
          return formatText(cur, upValue, 'up')
        } else {
          return formatText(cur, upValue, 'flat')
        }
      },

      resetSearch() {
        state.page = {
          pageNum: 1,
          pageSize: 10,
          total: 0
        }
        method.getTableData()
      },
    }
    onMounted(() => {
      method.getTableData()
      selectChannelList().then(res=>{
        state.channelList = res.data
      })
    })
    return {
      tableColumn,
      totalTableColumn,
      totalTableData:[],
      formRef,
      pagination,
      ...method,
      ...toRefs(state)
    }
  }
}
</script>

<style scoped>

</style>

